package io.github.hadyang.leetcode.bytedance;

/**
 * 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
 *
 * <p>( 例如，数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
 *
 * <p>搜索一个给定的目标值，如果数组中存在这个目标值，则返回它的索引，否则返回 -1 。
 *
 * <p>你可以假设数组中不存在重复的元素。
 *
 * <p>你的算法时间复杂度必须是 O(log n) 级别。
 *
 * <p>示例 1:
 *
 * <p>输入: nums = [4,5,6,7,0,1,2], target = 0 输出: 4 示例 2:
 *
 * <p>输入: nums = [4,5,6,7,0,1,2], target = 3 输出: -1
 *
 * @author haoyang.shi
 */
public class Array1017 {

  /**
   * https://www.cnblogs.com/keeya/p/9689927.html
   *
   * <p>基本就是 if else 判断
   *
   * @param nums
   * @param target
   * @return
   */
  public static int search(int[] nums, int target) {
    int start = 0, end = nums.length - 1;

    while (start <= end) {
      int mid = (start + end) / 2;
      if (nums[mid] == target) return mid;

      if (nums[mid] >= nums[start]) {
        if (target < nums[mid] && target >= nums[start]) {
          end = mid - 1;
        } else {
          start = mid + 1;
        }
      }

      if (nums[mid] <= nums[end]) {
        if (target > nums[mid] && target <= nums[end]) {
          start = mid + 1;
        } else {
          end = mid - 1;
        }
      }
    }

    return -1;
  }

  public static void main(String[] args) {
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 4));
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 5));
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 6));
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 7));
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 0));
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 1));
    System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 2));
    System.out.println(search(new int[] {5, 1, 3}, 5));
    System.out.println(search(new int[] {5, 1, 3}, 3));
    System.out.println(search(new int[] {4, 5, 6, 7, 8, 1, 2, 3}, 8));
    System.out.println(search(new int[] {5, 1, 2, 3, 4}, 1));
  }
}
